package com.demoweb.flappy.servlet;

import java.io.IOException;





import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.demoweb.model.dao.MemberDao;
import com.demoweb.model.dao.MembershipDao;
import com.demoweb.model.dto.Member;
import com.demoweb.model.dto.Membership;


@WebServlet("/flappy/account/login.action")
public class LoginServlet extends HttpServlet{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		// 1. 요청 데이터 읽기 (아이디, 비밀번호)
		String id = req.getParameter("memberId");
		String passwd = req.getParameter("passwd");
		
		// 2. 데이터 처리(db에서 조회)
		MembershipDao dao = new MembershipDao();
		Membership member = dao.getMemberByIdAndPasswd(id,passwd);
		
		// 3. 결과에 따라 이동 ( 성공 - home.action, 실패 -  loginfrom.action )
		String path = null;
		
		if(member == null) {
			path = "/demoweb/flappy/account/loginform.action";
		} else {
			// 로그인 성공
			// Session은 jsp 객체 servlet 에서는 가져다가 써야 한다.
			HttpSession session = req.getSession();
			session.setAttribute("loginuser", member);
			
			if(req.getParameter("returnuri") != null) {
				path = req.getParameter("returnuri");
			} else {
				path = "/demoweb/flappy/flappyMain.action";
			}
		}
		
		resp.sendRedirect(path);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		req.setCharacterEncoding("utf-8");
		doGet(req, resp);
	}
	
}
